<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-box">
        <uni-icons
          type="search"
          size="16"
          color="#999"
          @click="handleSearch"
        ></uni-icons>
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索衣物"
          focus
          confirm-type="search"
          @input="handleInput"
          @confirm="handleSearch"
        />
        <uni-icons
          v-if="searchKeyword"
          type="clear"
          size="16"
          color="#999"
          @click="clearSearch"
        ></uni-icons>
      </view>
      <text class="cancel-btn" @click="handleBack">取消</text>
    </view>

    <!-- 搜索内容 -->
    <view
      class="search-content"
      :style="{ paddingBottom: bottomSafeArea + 20 + 'rpx' }"
    >
      <!-- 搜索记录 -->
      <view
        v-if="!searchKeyword && searchHistory.length > 0"
        class="search-history"
      >
        <view class="history-header">
          <text class="history-title">搜索记录</text>
          <uni-icons
            type="trash"
            size="16"
            color="#999"
            @click="clearHistory"
          ></uni-icons>
        </view>
        <view class="history-list">
          <view
            v-for="(item, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="handleHistoryClick(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 热门搜索 -->
      <view v-if="!searchKeyword" class="hot-search">
        <view class="hot-header">
          <text class="hot-title">热门搜索</text>
        </view>
        <view class="hot-list">
          <view
            v-for="(item, index) in hotSearchList"
            :key="index"
            class="hot-item"
            @click="handleHotClick(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>

      <!-- 搜索结果 -->
      <view
        v-if="searchKeyword && searchResults.length > 0"
        class="search-results"
      >
        <!-- 筛选栏 -->
        <view class="results-header">
          <view class="sort-tabs">
            <view
              v-for="tab in sortTabs"
              :key="tab.value"
              class="sort-tab"
              :class="{ active: activeSort === tab.value }"
              @click="handleSortClick(tab.value)"
            >
              {{ tab.label }}
            </view>
            <!-- 筛选按钮 -->
            <view class="sort-tab filter-btn" @click="openFilter">筛选</view>
          </view>
        </view>

        <!-- 筛选弹窗 -->
        <uni-popup ref="filterPopup" type="right">
          <view class="filter-panel">
            <!-- 价格区间 -->
            <view class="filter-section">
              <text class="section-label">价格区间</text>
              <view class="price-range">
                <input
                  type="number"
                  v-model.number="filter.minPrice"
                  placeholder="最低价"
                  class="price-input"
                />
                <text class="divider">-</text>
                <input
                  type="number"
                  v-model.number="filter.maxPrice"
                  placeholder="最高价"
                  class="price-input"
                />
              </view>
            </view>
            <!-- 分类选择 -->
            <view class="filter-section">
              <text class="section-label">分类</text>
              <view class="category-list">
                <view
                  v-for="cat in categories"
                  :key="cat.value"
                  class="category-item"
                  :class="{ active: filter.category === cat.value }"
                  @click="filter.category = cat.value"
                >
                  {{ cat.label }}
                </view>
              </view>
            </view>

            <!-- 操作按钮 -->
            <view class="filter-actions">
              <button class="reset-btn" @click="resetFilter">重置</button>
              <button class="confirm-btn" @click="applyFilter">确定</button>
            </view>
          </view>
        </uni-popup>

        <!-- 结果列表 -->
        <view class="results-list">
          <scroll-view
            scroll-y="true"
            refresher-enabled="true"
            class="results-heigt"
            :refresher-triggered="refresherTriggered"
            @refresherrefresh="onPullDownRefresh"
            @scrolltolower="onReachBottom"
          >
            <view
              v-for="item in filteredResults"
              :key="item.id"
              class="result-item"
              @click="handleResultClick(item)"
            >
              <image
                :src="getFullImagePath(item.imageUrls)"
                mode="aspectFill"
                class="result-image"
              />
              <view class="result-info">
                <text class="result-name">{{ item.name }}</text>
                <text class="result-category">{{
                  getCategoryLabel(item.category)
                }}</text>
                <text class="result-desc">{{ item.description }}</text>
                <text class="result-price">￥{{ item.price }}</text>
                <text class="result-rating">评分: {{ item.rating }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 无搜索结果 -->
      <view
        v-if="searchKeyword && searchResults.length === 0 && !loading"
        class="no-results"
      >
        <image src="@/static/empty.png" class="no-results-img" />
        <text class="no-results-tip">试试其他关键词</text>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="loading-box">
        <view class="loading-spinner"></view>
        <text class="loading-text">搜索中...</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import { avatarUrlImg } from "@/api/config/http";
import { postSale } from "@/api/goods";
import { getCategoryAPI, getCategoryMapAPI } from "@/api/clothes";
import { onLoad } from "@dcloudio/uni-app";

const hasMore = ref(true); // 是否还有更多数据
const isLoadingMore = ref(false); // 加载更多状态
const refresherTriggered = ref(false); // 下拉刷新状态

// 基础图片地址，用于拼接完整路径
const baseImageUrl = avatarUrlImg;
const getFullImagePath = (path: string) => {
  return path.startsWith("http") ? path : baseImageUrl + path;
};

// 系统安全区（防止底部被遮挡）
const { safeArea } = uni.getSystemInfoSync();
const bottomSafeArea = ref(safeArea?.bottom ?? 0);
const params = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 输入和搜索相关状态
const searchKeyword = ref(""); // 当前搜索关键词
const loading = ref(false); // 是否正在加载
const searchHistory = ref<string[]>(["白色T恤", "牛仔裤", "运动鞋", "连衣裙"]); // 历史记录
const hotSearchList = ref<string[]>([
  "春季搭配",
  "商务正装",
  "休闲装",
  "运动装",
  "连衣裙",
  "外套",
]); // 热门搜索
interface CategoryItem {
  label: string;
  value: string;
}
// 搜索结果数据
const searchResults = ref<any[]>([]);

// 排序配置
const sortTabs = ref([
  { label: "综合", value: "default" },
  { label: "价格升序", value: "priceAsc" },
  { label: "价格降序", value: "priceDesc" },
  { label: "评价高", value: "rating" },
]);
const activeSort = ref("default"); // 当前选中的排序

// 筛选相关
const filterPopup = ref<any>(null); // 筛选弹窗引用
const filter = ref({
  minPrice: null, // 最低价
  maxPrice: null, // 最高价
  category: "", // 分类
});
// const categories = ["上衣", "裤子", "鞋子", "裙子", "外套"];
const categories = ref<CategoryItem[]>([
  { label: "上装", value: "1" },
  { label: "下装", value: "2" },
  { label: "外套", value: "3" },
  { label: "鞋子", value: "4" },
  { label: "背包", value: "5" },
  { label: "配饰", value: "6" },
  { label: "其他", value: "7" },
]);
// const categories = ref<CategoryItem[]>([]);

// 打开筛选弹窗
const openFilter = () => {
  filterPopup.value?.open();
};

// 重置筛选条件
const resetFilter = () => {
  filter.value = { minPrice: null, maxPrice: null, category: "" };
};

// 应用筛选（关闭弹窗即可，逻辑在 computed 里处理）
const applyFilter = () => {
  filterPopup.value?.close();
};

// 经过筛选和排序后的结果（computed 自动计算）
const filteredResults = computed(() => {
  let results = [...searchResults.value];

  // 筛选逻辑
  if (filter.value.minPrice) {
    results = results.filter((item) => item.price >= filter.value.minPrice);
  }
  if (filter.value.maxPrice) {
    results = results.filter((item) => item.price <= filter.value.maxPrice);
  }
  if (filter.value.category) {
    results = results.filter((item) => item.category === filter.value.category);
  }

  // 排序逻辑
  switch (activeSort.value) {
    case "priceAsc":
      results.sort((a, b) => a.price - b.price);
      break;
    case "priceDesc":
      results.sort((a, b) => b.price - a.price);
      break;
    case "rating":
      results.sort((a, b) => b.rating - a.rating);
      break;
  }

  return results;
});
const getCategoryLabel = (value: string) => {
  const cat = categories.value.find((c: CategoryItem) => c.value === value);
  return cat ? cat.label : value;
};
const getCategories = async () => {
  const res: any = await getCategoryMapAPI();
  if (res.code === "200") {
    categories.value = res.data;
    console.log("categories.value", categories.value);
  }
};
// 返回上一页
const handleBack = () => uni.navigateBack();

// 输入事件
const handleInput = (e: any) => {
  const value = e.detail.value;
  searchKeyword.value = value;
  if (!value.trim()) searchResults.value = [];
};
const recordList = ref<any[]>([]);
const size = ref(5);
// 模拟搜索逻辑（实际应调用 API）
const performSearch = (keyword: string, isRefresh = false) => {
  loading.value = true;
  if (isRefresh) {
    params.pageNum = 1;
    hasMore.value = true;
  }
  if (!hasMore.value) return;
  isLoadingMore.value = true;
  console.log("keyowrd", keyword);
  setTimeout(async () => {
    const res: any = await postSale({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      name: keyword,
    });
    const dataList = res.data.records;
    const newRecords = dataList.map((item: any) => ({
      ...item,
      imageUrls: item.imageUrls?.[0],
    }));

    if (isRefresh) {
      recordList.value = newRecords;
    } else {
      recordList.value.push(...newRecords);
    }
    console.log("获取得到的数据结果", recordList.value);
    searchResults.value = recordList.value as any[];
    hasMore.value = newRecords.length >= size.value;
    params.pageNum++;
    isLoadingMore.value = false;
    refresherTriggered.value = false;
  }, 500);
  loading.value = false;
};
// // 下拉刷新处理
const onPullDownRefresh = () => {
  refresherTriggered.value = true;
  performSearch(searchKeyword.value, true);
  uni.showToast({
    title: "刷新成功",
    icon: "success",
    duration: 300,
  });
};
// 滚动到底部处理
const onReachBottom = () => {
  if (hasMore.value && !isLoadingMore.value) {
    performSearch(searchKeyword.value);
  }
};
// 点击搜索（键盘确认或图标点击）
const handleSearch = () => {
  // ✅ 每次搜索必须重置分页
  if (searchKeyword.value.trim()) {
    params.pageNum = 1;
    hasMore.value = true;
    recordList.value = [];
    performSearch(searchKeyword.value);
    addToHistory(searchKeyword.value);
  }
};

// 清空搜索框
const clearSearch = () => {
  searchKeyword.value = "";
  searchResults.value = [];
};

// 添加搜索历史
const addToHistory = (keyword: string) => {
  if (!searchHistory.value.includes(keyword)) {
    searchHistory.value.unshift(keyword);
    if (searchHistory.value.length > 20)
      searchHistory.value = searchHistory.value.slice(0, 20);
  }
};

// 点击历史记录
const handleHistoryClick = (keyword: string) => {
  searchKeyword.value = keyword;
  performSearch(keyword);
};

// 点击热门搜索
const handleHotClick = (keyword: string) => {
  searchKeyword.value = keyword;
  performSearch(keyword);
  addToHistory(keyword);
};

// 清空历史记录
const clearHistory = () => {
  uni.showModal({
    title: "提示",
    content: "确定要清空搜索记录吗？",
    success: (res) => {
      if (res.confirm) searchHistory.value = [];
    },
  });
};

// 点击某个搜索结果（跳转到详情页）
const handleResultClick = (item: any) =>
  uni.navigateTo({ url: `/pages/goods/goods?id=${item.id}` });

// 切换排序
const handleSortClick = (value: string) => {
  activeSort.value = value;
};
onLoad(() => {
  getCategories();
});
</script>

<style lang="scss">
page {
  height: 100%;
  width: 100%;
  overflow: hidden;
}
</style>
<style scoped lang="scss">
.search-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;

  .search-input-box {
    flex: 1;
    display: flex;
    align-items: center;
    background: #f5f5f5;
    border-radius: 20rpx;
    padding: 16rpx 20rpx;
    margin-right: 20rpx;

    .search-input {
      flex: 1;
      margin: 0 16rpx;
      font-size: 28rpx;
      background: transparent;
      border: none;
      outline: none;
    }
  }

  .cancel-btn {
    font-size: 28rpx;
    color: #92beab;
  }
}

.search-content {
  flex: 1;
  //   padding: 20rpx 20rpx 0 20rpx;
}

.search-history {
  margin-bottom: 40rpx;
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    .history-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    .history-item {
      padding: 12rpx 24rpx;
      background: #fff;
      border-radius: 20rpx;
      font-size: 26rpx;
      color: #666;
      border: 1rpx solid #eee;
    }
  }
}

.hot-search {
  .hot-header {
    margin-bottom: 20rpx;
    .hot-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .hot-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    .hot-item {
      padding: 12rpx 24rpx;
      background: #fff;
      border-radius: 20rpx;
      font-size: 26rpx;
      color: #666;
      border: 1rpx solid #eee;
    }
  }
}

.search-results {
  .results-header {
    margin-bottom: 20rpx;
    .results-title {
      font-size: 28rpx;
      color: #666;
    }
  }
  .results-list {
    height: 1200rpx;
    .results-heigt {
      // padding: 0 20rpx;
      height: 100%;
    }
    .result-item {
      padding: 20rpx;
      display: flex;
      height: 200rpx;
      flex-shrink: 0;
      background: #fff;
      padding: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      .result-image {
        width: 200rpx;
        height: 200rpx;
        background-color: cadetblue;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }

      .result-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .result-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 8rpx;
        }

        .result-category {
          font-size: 26rpx;
          color: #92beab;
          margin-bottom: 8rpx;
        }

        .result-desc {
          font-size: 24rpx;
          color: #999;
          line-height: 1.4;
        }
      }
    }
  }
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;

  .no-results-img {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  .no-results-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
  }

  .no-results-tip {
    font-size: 26rpx;
    color: #999;
  }
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;

  .loading-spinner {
    width: 48rpx;
    height: 48rpx;
    border: 6rpx solid #92beab;
    border-top: 6rpx solid transparent;
    border-radius: 50%;
    animation: spin 0.5s linear infinite;
    margin-bottom: 20rpx;
  }

  .loading-text {
    color: #92beab;
    font-size: 28rpx;
  }
}
/* 保持原样式 + 新增 */
.sort-tabs {
  display: flex;
  padding: 10rpx 20rpx;
  gap: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;

  .sort-tab {
    font-size: 26rpx;
    padding: 10rpx 20rpx;
    border-radius: 20rpx;
    color: #666;
    background: #f5f5f5;
  }
  .active {
    color: #fff;
    background: #92beab;
  }
  .filter-btn {
    margin-left: auto;
    background: #eee;
  }
}

.filter-panel {
  background: #fff;
  padding: 20rpx;
  border-radius: 20rpx 20rpx 0 0;
  .filter-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  .filter-section {
    margin-bottom: 20rpx;
    .section-label {
      font-size: 28rpx;
      margin-bottom: 10rpx;
      display: block;
    }
    .price-range {
      display: flex;
      align-items: center;
      gap: 10rpx;
    }
    .price-input {
      flex: 1;
      border: 1rpx solid #ccc;
      padding: 10rpx;
      border-radius: 8rpx;
    }
    .divider {
      padding: 0 10rpx;
    }
    .category-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
    }
    .category-item {
      padding: 10rpx 20rpx;
      border: 1rpx solid #ccc;
      border-radius: 20rpx;
      font-size: 26rpx;
    }
    .category-item.active {
      background: #92beab;
      color: #fff;
      border-color: #92beab;
    }
  }
  .filter-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
  }
  .reset-btn {
    flex: 1;
    margin-right: 20rpx;
    background: #f5f5f5;
  }
  .confirm-btn {
    flex: 1;
    background: #92beab;
    color: #fff;
  }
}

.result-price {
  color: #e64340;
  font-size: 26rpx;
  margin-top: 8rpx;
}
.result-rating {
  color: #ff9500;
  font-size: 24rpx;
  margin-top: 4rpx;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
